package main

import (
	"flag"
	"fmt"
	"im/global"
	"im/model/chat"
	"im/router"
	"im/service"
	"log"
	"net/http"
)

var addr = flag.String("addr", ":9000", "http service address")

func main() {

	// 初始化配置
	global.InitConfig()
	global.InitMysql()
	global.InitRedis()

	//
	global.Hub = chat.CreateHub()
	// 启动 hub 协程
	go service.Run(global.Hub)

	// 配置路由
	r := router.Router()

	// 配置 websocket 路由
	// http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
	// 	fmt.Printf("r.URL: %v\n", r.URL)
	// 	service.WsHandler(hub, w, r)
	// })

	// 启动服务
	err := http.ListenAndServe(*addr, r)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}

	/**
	srv := &http.Server{
		Addr:    ":9000",
		Handler: r,
	}

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	// catching ctx.Done(). timeout of 5 seconds.
	select {
	case <-ctx.Done():
		log.Println("timeout of 5 seconds.")
	}
	log.Println("Server exiting")
	*/
	fmt.Printf("服务启动成功.....")
}
